// pages/myself/integral/RedeemDetails.js
var Zan = require('../../../dist/index');
var WxParse = require('../../../wxParse/wxParse.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
var eventStatus = 0; // 0=没选规格;1=加入购物车;2=立即购买
var start1 = 0;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {
  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    listSpec: [],
    showDialog: false,
    count: 0,
    currProPrice: 0,
    currChangeIntegral:0,
    oldPrice: 0,
    selectedSpec: null,
    num: 0,
    specId: null,
    TenantDistribution: [],
    specArr: [],
    specArrCon: [],
    specArray: [],
    title: '',
    productId: '',
    integral: 0,
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoCallback = res => {
        bind(options);
      }
    }
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    // wx.getUserInfo({
    //   success: res => {
    //     this.setData({
    //       nickName: res.userInfo.nickName,
    //     })
    //   }
    // })

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })

    this.setData({
      productId: options.productId,
      integral: app.globalData.userInfo.integral,
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 560
      }
      
    })
    // console.log(this.data.integral);
    network._post_json(this, api.getProductDetails, { productId: options.productId }, success);
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    eventStatus = 0;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.product.title,
      path: '/pages/myself/integral/RedeemDetails?shared=' + app.globalData.userInfo.id + '&ipsId=' + this.data.product.id,
      // imageUrl: this.data.saleInfo.qrCode,
      success: function (res) {
        // 转发成功
        // if (res.shareTickets) {
        //   wx.getShareInfo({
        //     shareTicket: res.shareTickets,
        //     success: function (res) {
        //       network._post_json(this, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
        //     },
        //     fail: function (res) {
        //       // 转发失败
        //       network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        //     }
        //   })
        // } else {
        //   network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        // }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 弹出框开关
   */
  Specclose: function (e) {
    this.setData({
      specDialog: !this.data.specDialog,
    })
  },

  // selected: function(e){    
  //   var checkFlag = isSelectedOk(this);
  //   if (checkFlag == -1) {
  //     this.showZanTopTips(1, '您的积分为' + this.data.integral + "，不够兑换");
  //   } else {
  //     toPayPage(this);
  //   }
  // },
 
  /**
   * 进入下一步提交订单
   */
  next: function (e) {
    if (this.data.count<=0){
      this.showZanTopTips(1, '请先选择数量');
      return false;
    }
    var checkFlag = isSelectedOk(this, this.data.product, this.data.count);
    // console.log("您的积分为");
    // console.log(this.data.integral);
    if (checkFlag == -3) {
      this.showZanTopTips(1,'您的积分为' + this.data.integral + "，不够兑换");
    } else {
      toPayPage(this);
    }
    
  },
  nextTips:function(e){
    this.setData({
      specDialog: !this.data.specDialog,
    })
  },
  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      this.setData({
        count: this.data.count,
      });
      calcPoint(this);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    var counts = parseInt(this.data.count) + 1;
    
    //校验数量
    var checkFlag = isSelectedOk(this, this.data.product, counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
      return false;
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      return false;
    } else if (checkFlag == -3) {
      this.showZanTopTips(this.prompt, "积分不足");
      return false;
    } else {
      this.data.count++;
      this.setData({
        count: this.data.count,
      });
      calcPoint(this);
    }
  },
  
  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */

  formSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },
  
  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },

  //规格显示
  selectSpec: function (e) {
    var title = e.currentTarget.dataset.title;
    var productId = e.currentTarget.dataset.id;
    this.data.specArr = JSON.parse(this.data.product.spec);

    let specArrCon = [];
    for (var n = 0; n < this.data.specArr.length; n++) {
      let spec = {};
      let specDetailArr = [];
      spec.specType = this.data.specArr[n].specType;
      for (var i = 0; i < this.data.specArr[n].specDetails.length; i++) {
        let specDetail = {};
        specDetail.name = this.data.specArr[n].specDetails[i];
        specDetail.class = '';
        if (i == 0) {
          specDetail.class = "active";
        }
        specDetailArr.push(specDetail);
      } 
      specArrCon.push(spec);
      spec.specDetails = specDetailArr;
    }
    this.setData({
      specTitle: title,
      specArrCon: specArrCon,
      specDialog: !this.data.specDialog,
      productId: productId,
      specDetails1: specArrCon[0].specDetails[0].name,
      specDetails2: specArrCon[1] != undefined ? specArrCon[1].specDetails[0].name : '',
      specDetails3: specArrCon[2] != undefined ? specArrCon[2].specDetails[0].name : '',
      
      currProPrice: this.data.currProPrice,
      currChangeIntegral: this.data.currChangeIntegral
    })

    if (this.data.count < 1) {
      this.data.count = 1;
      this.setData({
        count: this.data.count,
      });
    }
    getProductPrice(this);
  },
  //选择一个规格后
  specSelect: function (e) {
    console.log(this.data.specArrCon);
    var currData = e.currentTarget.dataset;
    var fatidx = currData.fatidx;
    var subidx = currData.subidx;
    var currBind = this.data.specArrCon[fatidx].specDetails[subidx];
    currBind.class = "active";

    //处理当前选择的规格类型的其他规格
    for (var n = 0; n < this.data.specArrCon[fatidx].specDetails.length; n++) {
      if (this.data.specArrCon[fatidx].specDetails[n].class == "active" && subidx != n) {
        this.data.specArrCon[fatidx].specDetails[n].class = "";
      }
    }

    this.setData(this.data);
    //计算所选规格价格
    var selectedSpec = [];
    for (var m = 0; m < this.data.specArrCon.length; m++) {
      for (var n = 0; n < this.data.specArrCon[m].specDetails.length; n++) {
        if (this.data.specArrCon[m].specDetails[n].class == "active") {
          selectedSpec.push(this.data.specArrCon[m].specDetails[n].name);
        }
      }
    }
    this.setData({
      specDetails1: selectedSpec[0],
      specDetails2: selectedSpec[1] != undefined ? selectedSpec[1] : '',
      specDetails3: selectedSpec[2] != undefined ? selectedSpec[2] : '',
    })
    getProductPrice(this);
  }
  
}))
//Page结束

var toPayPage = function(that){
  //跳到支付页
  that.setData({
    showDialog: false,
  });
  try {
    wx.setStorageSync('RedeemDetailsData', that.data);
  } catch (e) {
  }
  wx.navigateTo({
    url: '/pages/pay/IntegralPay',
  })
}

//校验当前选择的规格及数量是否可以购买
var isSelectedOk = function (that, products, counts) {
  // console.log("校验当前选择的规格及数量是否可以购买");
  // console.log(counts);
  
  // console.log(that.data.currChangeIntegral);
  // console.log(parseInt(that.data.integral));
  // console.log(parseInt(that.data.currChangeIntegral) * that.data.count);
  if (parseInt(that.data.integral) < parseInt(that.data.currChangeIntegral) * counts) {
    //规格选了，但是积分不够
    return -3;
  }
  
  //多规格
  if (products.specClass == 2) {
    if (that.data.isStore == 0) {
      if (that.data.limitCount != 0) {
        if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (that.data.limitCount != 0) {
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }
    }
  } else {
    if (products.isStore == 0) {
      if (products.limitCount != 0) {
        if (counts > products.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (products.limitCount != 0) {
        if (products.storeCount <= 0 || products.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > products.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (products.storeCount <= 0 || products.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }

    }
  }
  
}

// 获取商品列表结果
var success = function (that, res) {
  if (res.data.data) {
    that.setData({
      product: res.data.data,
      currProPrice: res.data.data.currentPrice,
      currChangeIntegral: res.data.data.integralPrice,
      detail: res.data.data.detail.replace(/\<img/gi, '<img style="width:100%;height:auto" ').replace(/\white-space: nowrap;/gi, '').replace(/\white-space:nowrap;/gi, '')
    })
    // WxParse.wxParse('details', 'html', res.data.data.detail, that, 0);
  }
}

//计算当前价格
var calcPoint = function (that) {
  //多规格
  that.setData({
    currProPrice: that.data.product.currentPrice
  })
}

//获取多规格商品分类价格
var getProductPrice = function (that) {
  // console.log("获取多规格商品分类价格");
  console.log(that.data.product);

  //价格
  network._post_json(that, api.getProductPrice, { productId: that.data.product.id, specDetails1: that.data.specDetails1, specDetails2: that.data.specDetails2, specDetails3: that.data.specDetails3 }, successPrice);
}
var successPrice = function (that, res) {
  that.setData({
    count: 0
  })
  if (res.data.data) {
    that.setData({
      currProPrice: res.data.data.currentPrice ? res.data.data.currentPrice : 0,
      currChangeIntegral: res.data.data.integralPrice ? res.data.data.integralPrice : 0,
      specId: res.data.data.specId,
      limitCount: parseInt(res.data.data.limitCount),
      storeCount: parseInt(res.data.data.storeCount),
      isStore: res.data.data.isStore,
    })
  }
}

var bindSuccess = function (that, res) {
  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        integral: app.globalData.userInfo.integral
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}